import os
from flask import Flask

import time

import logging

from apps.settingApi.api.chart.url import chart_api
from apps.settingApi.api.printCode.url import printcode_api
from apps.settingApi.api.switchDatabaseExample.url import switch_database_example_api
from comm.sqlalchemyConfig import init_ext
from setting import envs

# 注册路由
from apps.settingApi.api.users.url import user_api
from apps.settingApi.api.dict.url import setting_dict_api
from apps.settingApi.api.lessees.url import lessees_api
from apps.settingApi.api.funs.url import funs_api
from apps.settingApi.api.role.url import setting_role_api
from apps.settingApi.api.basic.url import setting_basic_api
from apps.settingApi.api.file.url import file_api
from apps.settingApi.api.timerTask.url import timer_task_api
from apps.settingApi.api.timerTask.url import timer_task_api


# 终端日志的输出格式
logging.basicConfig(format='%(asctime)s - %(levelname)s--->: %(message)s',
                    level=logging.DEBUG,
                    filemode='a')
# Windows日志
from concurrent_log_handler import ConcurrentRotatingFileHandler
def createLogFile(level):
    # 创建一个logger
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)  # Log等级总开关

    # 创建一个handler，用于写入日志文件
    rq = time.strftime('%Y%m%d', time.localtime(time.time()))
    # log_date = rq[:10]
    log_path = os.getcwd() + '/Logs/'
    isExists = os.path.exists(log_path)
    # # 判断结果
    if not isExists:
        os.makedirs(log_path)
    log_name = os.getcwd() + '/Logs/{0}'.format(rq)  + '.log'
    # fh = logging.FileHandler(log_name, mode='a')
    fh = ConcurrentRotatingFileHandler(log_name, maxBytes=1024 * 1024*5, backupCount=100,encoding='utf-8')
    fh.setLevel(level)  # 输出到file的log等级的开关

    # 定义handler的输出格式
    formatter = logging.Formatter("%(asctime)s - %(levelname)s--->: %(message)s")
    fh.setFormatter(formatter)
    logger.addHandler(fh)

def create_app():
    # app = Flask(__name__)
    PATH_ROOT = os.path.abspath(os.curdir)
    app = Flask(__name__,template_folder=PATH_ROOT+'\\templates',static_folder=PATH_ROOT+"\\templates/static")
    # 创建app实例前先配置好日志文件
    # Windows日志
    createLogFile('DEBUG')

    # 初始化配置
    app.config.from_object(envs.get("pro"))
    # 初始化app
    init_ext(app)
    # 注册用户模块
    user_api.init_app(app)
    # 字典模块
    setting_dict_api.init_app(app)
    # 注册租户模块
    lessees_api.init_app(app)
    # 注册模块
    funs_api.init_app(app)
    # 注册角色模块
    setting_role_api.init_app(app)
    # 基础资料注册
    setting_basic_api.init_app(app)
    # 注册文件管理
    file_api.init_app(app)
    # 打印模块注册
    printcode_api.init_app(app)
    # 多数据库操作实例
    switch_database_example_api.init_app(app)
    # 注册定时任务
    timer_task_api.init_app(app)
    # 看板
    chart_api.init_app(app)
    return app